#include "Common.h"

void LUAUnit::SetHealth(float pct)
{
	if(!cr)
		return;
	if(pct > 100.0f)
		pct = 100.0f;
	else if(pct <= 0)
		pct = 0.1f;
	ui32 maxh = cr->GetUI32Value(UNIT_FIELD_MAXHEALTH);
	ui32 newh = ceil((maxh * pct) / 100.0f);
	cr->SetUI32Value(UNIT_FIELD_HEALTH, newh);
}

void LUAUnit::SetHealth(ui32 absval)
{
	if(!cr)
		return;
	absval = min(absval, cr->GetUI32Value(UNIT_FIELD_MAXHEALTH));
	cr->SetUI32Value(UNIT_FIELD_HEALTH, absval);
}

LUAUnit LUAUnit::SpawnCreature(ui32 entry, float x, float y, float z, float o)
{
	LUAUnit* un = new LUAUnit;
	if(!cr)
		return *un;
	MapHandler* hndl = cr->GetMapHandler();
	if(!hndl)
		return *un;
	un->cr = hndl->GetMapInterface()->SpawnCreature(entry, x, y, z, o);
	return *un;
}

LUAUnit LUAUnit::SpawnCreature(ui32 entry)
{
	LUAUnit* un = new LUAUnit;
	if(!cr)
		return *un;
	MapHandler* hndl = cr->GetMapHandler();
	if(!hndl)
		return *un;
	un->cr = hndl->GetMapInterface()->SpawnCreature(entry, cr->GetPosition()._x, cr->GetPosition()._y, cr->GetPosition()._z, cr->GetOrientation());
	return *un;
}

LUAVector LUAUnit::GetPosition()
{
	LUAVector* v = new LUAVector(0.0f, 0.0f, 0.0f, 0);
	if(!cr)
		return *v;
	v->_x = cr->GetPosition()._x;
	v->_y = cr->GetPosition()._y;
	v->_z = cr->GetPosition()._z;
	v->_map = cr->GetMapHandler()->GetMapId();
	return *v;
}

void LUAUnit::SetUI32Value(ui32 index, ui32 value)
{
	switch(index)
	{
	case UNIT_NPC_FLAGS:
	case UNIT_NPC_EMOTESTATE:
	case UNIT_FIELD_FACTIONTEMPLATE:
	case OBJECT_FIELD_SCALE_X:
		break;

	default:
		return;
	}
	if(!cr)
		return;
	cr->SetUI32Value(index, value);
}

ui32 LUAUnit::GetUI32Value(ui32 index)
{
	switch(index)
	{
	case UNIT_NPC_FLAGS:
	case UNIT_NPC_EMOTESTATE:
	case UNIT_FIELD_FACTIONTEMPLATE:
	case OBJECT_FIELD_SCALE_X:
		break;

	default:
		return 0;
	}
	if(!cr)
		return 0;
	
	return cr->GetUI32Value(index);
}

scope LUAUnit::RegisterLUAUnit()
{
	return
		class_<LUAUnit>("LUAUnit")
		.def("SpawnUnitHere", (LUAUnit (LUAUnit::*)(ui32))&LUAUnit::SpawnCreature)
		.def("SpawnUnitAt", (LUAUnit (LUAUnit::*)(ui32, float, float, float, float))&LUAUnit::SpawnCreature)
		.def("SetHealthAbs", (void (LUAUnit::*)(ui32))&LUAUnit::SetHealth)
		.def("SetHealthPct", (void (LUAUnit::*)(float))&LUAUnit::SetHealth)
		.def("GetPosition", &LUAUnit::GetPosition)
		.def("GetOrientation", &LUAUnit::GetOrientation)
		.enum_("constants")
		[
			value("UNIT_FIELD_FACTIONTEMPLATE", UNIT_FIELD_FACTIONTEMPLATE),
			value("UNIT_NPC_EMOTESTATE", UNIT_NPC_EMOTESTATE),
			value("UNIT_NPC_FLAGS", UNIT_NPC_FLAGS),
			value("OBJECT_FIELD_SCALE_X", OBJECT_FIELD_SCALE_X)
		]
		.def("SetUI32Value", &LUAUnit::SetUI32Value)
		.def("GetUI32Value", &LUAUnit::GetUI32Value)
		.def("GetEntry", &LUAUnit::GetEntry);
}